﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Elf.Data.Entity.Interfaces;
using Elf.Common;
using System.Globalization;

namespace Elf.Data.Entity
{
    /// <summary>
    /// Utilities to create repositories.
    /// </summary>
    public static class RepositoryUtility
    {
        private static readonly IDictionary<Type, object> _repositories = new Dictionary<Type, object>();
        /// <summary>
        /// Gets the repositories.
        /// </summary>
        public static IDictionary<Type, object> Repositories
        { get { return _repositories; } }

        /// <summary>
        /// Gets the generic repository.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <typeparam name="TContext">The type of the context.</typeparam>
        /// <param name="repositoryType">Type of the repository.</param>
        /// <returns></returns>
        public static IRepository<TEntity, TContext> GetGenericRepository<TEntity, TContext>(Type repositoryType)
            where TEntity : class, IEntityBase, new()
            where TContext : ContextBase, new()
        {
            if (typeof(TEntity).GetInterface(typeof(IEntityId).FullName) == null)
                throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "Type {1} does not implement interface {0}.", typeof(IEntityId).Name, typeof(TEntity).Name));
            if (Repositories.ContainsKey(typeof(TEntity)))
            {
                //Posibility to mock a repository on the static list.
                return (IRepository<TEntity, TContext>)Repositories[typeof(TEntity)];
            }
            else
            {
                return ActivatorExtension.CreateGenericInstance<IRepository<TEntity, TContext>>(repositoryType, typeof(TEntity));
            }
        }

        /// <summary>
        /// Gets the generic repository.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <typeparam name="TContext">The type of the context.</typeparam>
        /// <returns></returns>
        public static IRepository<TEntity, TContext> GetGenericRepository<TEntity, TContext>()
            where TEntity : class, IEntityBase, new()
            where TContext : ContextBase, new()
        {
            if (Repositories.ContainsKey(typeof(TEntity)))
            {
                //Posibility to mock a repository on the static list.
                return (IRepository<TEntity, TContext>)Repositories[typeof(TEntity)];
            }
            else
            {
                return ActivatorExtension.CreateGenericInstance<IRepository<TEntity, TContext>>(typeof(Repository<,>), typeof(TEntity), typeof(TContext));
            }
        }
    }
}
